package com.tinygray.lock;

import sun.misc.Cache;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: tinygray
 * @Description: 公众号:Madison龙少，关注我你会越来越优秀。
 * @className: CasLockDemo
 * @create: 2021-05-08 17:40
 */
public class CasLockDemo {

    //创建原子线程引用
    AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();

    public void myLock() {

        //获取当前进来的线程
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "\t" + "come in ");
        while (!threadAtomicReference.compareAndSet(null, thread)) {

        }
    }
    public void myUnLock(){
        //获取当前线程
        Thread thread = Thread.currentThread();
        //线程用完之后设置成null，来让其他线程进来使用
        threadAtomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t" + "invoked myUnLock()");
    }

    public static void main(String[] args) {
        CasLockDemo casLockDemo = new CasLockDemo();

        new Thread(() -> {
            casLockDemo.myLock();
            try {
                Thread.currentThread().join(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            casLockDemo.myUnLock();
        }, "AAA").start();

        //让主线程睡眠1s 保证AAA线程先执行
        try {
            Thread.currentThread().join(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            casLockDemo.myLock();
            try {
                Thread.currentThread().join(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            casLockDemo.myUnLock();
        }, "BBB").start();
    }

}
